package com.edroid.autorunner.um;

import java.io.File;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.List;

import android.app.AndroidAppHelper;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.support.v4.os.EApkHooker;
import android.support.v4.os.EConstants;
import android.support.v4.os.EHook;
import android.support.v4.os.ESystem;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.edroid.autorunner.AutoRunActivity;
import com.edroid.autorunner.Statics;
import com.example.auto.ScriptMaker;
import com.example.auto.ScriptRunner;
import com.example.auto.ScriptRunner.CMDS;
import com.example.auto.UserHandlerContext;
import com.example.service.SystemServiceGetter;
import com.example.utils.KvTool;
import com.example.utils.Logger;
import com.example.utils.Shell;

public class UserManager{
	public static final Logger log = Logger.create("UserManager");
	
	private Context mContext;
	int runTime;
	boolean enableScript  = true;
	boolean recodeScript;
	List<DayInfo> dayInfos;
	String app;
	String scriptPath;
	boolean isMain;
	
	private static int count;
	public static boolean toDesk = false;
	private static boolean useWalic = false;
	private static boolean isRunningInWifiMode = false;//录制脚本时检查是WIFI还是移动网络

	static UserInfo currentUserInfo;
	static UserManager sInstance;
	
	
	public static UserInfo currentUserInfo() {
		if(currentUserInfo == null)
			currentUserInfo = UserMaker.getOriginalUser();
		return currentUserInfo;
	}
	
	public void makeNewUser(UserInfo userInfo) {
		UserMaker.makeNewUser(userInfo);
	}
	
	public static void printDeviceInfo(Context context) {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);  
		
        StringBuilder sb = new StringBuilder();  
        sb.append("\nDeviceId(IMEI) = " + tm.getDeviceId());  
        sb.append("\nLine1Number = " + tm.getLine1Number());  
        sb.append("\nNetworkCountryIso = " + tm.getNetworkCountryIso());  
        sb.append("\nNetworkOperator = " + tm.getNetworkOperator());  
        sb.append("\nNetworkOperatorName = " + tm.getNetworkOperatorName());  
        sb.append("\nNetworkType = " + tm.getNetworkType());  
        sb.append("\nPhoneType = " + tm.getPhoneType());  
        sb.append("\nSimCountryIso = " + tm.getSimCountryIso());  
        sb.append("\nSimOperator = " + tm.getSimOperator());  
        sb.append("\nSimOperatorName = " + tm.getSimOperatorName());  
        sb.append("\nSimSerialNumber = " + tm.getSimSerialNumber());  
        sb.append("\nSimState = " + tm.getSimState());  
        sb.append("\nSubscriberId(IMSI) = " + tm.getSubscriberId());  
        
        sb.append("\nmodel = " + Build.MODEL);
        sb.append("\nsdkint = " + Build.VERSION.SDK_INT);
       
        //Conectioni
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        sb.append("\nmac = " + wm.getConnectionInfo().getMacAddress());
        
        log.i("", "------------ device info -------- \n" 
        		+ sb.toString());
	}
	
	private void initUserInfo(KvTool kv) {
		UserInfo def = UserMaker.initOriginal(mContext);
		
		UserInfo userInfo = new UserInfo().read(kv, def);
		log.i("read userInfo:" + userInfo);
		UserMaker.applayUserInfo(userInfo);
		
		currentUserInfo = userInfo;
	}
	
	public static synchronized void init(Application app) {
	    if(sInstance== null)
	        sInstance = new UserManager(app);
	}
	
	public static UserManager getInstance() {
        return sInstance;
    }
	
	private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
        String SYSTEM_REASON = "reason";
        String SYSTEM_HOME_KEY = "homekey";
        String SYSTEM_HOME_KEY_LONG = "recentapps";
         
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                     //表示按了home键,程序到了后台
//                    Toast.makeText(context, "home", Toast.LENGTH_SHORT).show();
                    
                    ScriptMaker.addCMD(CMDS.home); //添加返回桌面事件
                    UserHandlerContext.getInstance().backApp(3000);
                } else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
                    //表示长按home键,显示最近使用的程序列表
//                    Toast.makeText(context, "recent task", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };
    
    public void onExit() {
    	if(isMain) {
			if(recodeScript) {
				ScriptMaker.stopRecording(scriptPath);
			}
		}
	}
	
	private UserManager(final Context context) {
	    sInstance = this;
		this.mContext = context.getApplicationContext();
		UserHandlerContext.getInstance().init(context);
		if(this.mContext == null) {
			this.mContext = context;
		}
		
		app = AndroidAppHelper.currentPackageName();
		log.i("ps=" + EApkHooker.getPsName());
		log.i("app=" + app);
		
		//主进程！(同一个应用可能存在不同进程）
		isMain = app.equals(EApkHooker.getPsName()); 
		
		KvTool sp = AutoRunActivity.getDataPreferences(app);
		
		long startTime = sp.getLong("time", 0);
		long delayTime = System.currentTimeMillis() - startTime;
		
		runTime = sp.getInt("runTime", 30);
		toDesk = sp.getBoolean("toDesk", false);
		useWalic = sp.getBoolean("useWalic", false);
		isRunningInWifiMode = sp.getBoolean("isRunningInWifiMode", false);
		
		EHook.sHookResolution = sp.getBoolean("hookResolution", false);

		//初始化全局变量
		Statics.appTime = sp.getInt("appTime", 60);
		
		log.e("process delay time=" + delayTime + ", legth=" + runTime);
		//!isMain ||
		
		if((delayTime < runTime*1000) && sp.getBoolean("auto", false)) {
			enableScript = sp.getBoolean("script", true);
			recodeScript = sp.getBoolean("recode", true);
			
			initUserInfo(sp);

			scriptPath = getUsableScriptPath();
			
			if(isMain) {
				if(recodeScript) {
					ESystem.hookTime=false;
					if (useWalic) {
						//walic 录制 
					} else {
						ScriptMaker.startRecord();
						mContext.registerReceiver(mHomeKeyEventReceiver, 
				                new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
					}
				} else {
					ESystem.hookTime=true;
					if (useWalic) {
						//walic 播放
					} else {
						//看看脚本在不在
						final File scriptFile = new File(scriptPath);
						
						if(enableScript && scriptFile.exists()){
							ScriptRunner.run(scriptPath, runTime*1000);
						}
					}
				}
			}
			
			//结束进程
			UserHandlerContext.getInstance().getHandler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					if(isMain) {
						if(recodeScript) {
							ScriptMaker.stopRecording(scriptPath);
						}
					}
					log.e(">>>>>>>>> foceStop");
					SystemServiceGetter.getPermissionService().forceStopPackage(app);
				}
			}, runTime*1000);
		}
		
		//捕获到异常后重启自己
		Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
			@Override
			public void uncaughtException(Thread thread, Throwable ex) {
				log.e("未捕获异常：");
				try {
					PrintWriter pw = new PrintWriter("/sdcard/exception.txt");
					pw.print("sdk_int:");
					pw.println(currentUserInfo.sdk_int);
					ex.printStackTrace(pw);
					ex.printStackTrace();
					pw.close();
					ex.printStackTrace();
					Thread.sleep(3000);
				} catch (Exception e) {
				}
//				mContext.sendBroadcast(new Intent("com.edroid.intent.action.runapk"));
			}
		});
		count++;
		Toast.makeText(context, "User Ok!"+count, Toast.LENGTH_SHORT).show();
	}

	public static String getScriptPath(String pkg) {
		return EConstants.SCRIPTS_PATH + pkg;
	}
	
	public static String getScriptPath_w(String pkg) {
		return getScriptPath(pkg) + "_w";
	}
	
	public static String getScriptPath_m(String pkg) {
		return getScriptPath(pkg) + "_m";
	}

	/**
	 * 获得可用的脚本路径
	 * @return
	 */
	private String getUsableScriptPath() {
		String wifi = getScriptPath_w(app);
		String mobi = getScriptPath_m(app);
		if (recodeScript) {
			return isRunningInWifiMode ? wifi : mobi;
		} else {
			// 播放，尽可能返回一个存在的脚本文件路径
			if (isRunningInWifiMode) {
				return new File(wifi).exists() ? wifi : mobi;
			} else {
				return new File(mobi).exists() ? mobi : wifi;
			}
		}
	}
}
